package cc.idoone.spring_boot_hello.h2;

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;

import javax.sql.DataSource;

@Configuration
public class H2DataSourceConfiguration {

	@Bean(name = "h2DataSource")
	@ConfigurationProperties(prefix = "spring.datasource.h2")
	public DataSource h2DataSource() {
		return DataSourceBuilder.create().build();
	}

	@Bean(name = "h2JdbcTemplate")
	public JdbcTemplate h2JdbcTemplate(@Qualifier("h2DataSource") DataSource dataSource) {
		return new JdbcTemplate(dataSource);
	}

	@Bean(name = "h2NamedJdbcTemplate")
	public NamedParameterJdbcTemplate h2NamedJdbcTemplate(@Qualifier("h2DataSource") DataSource dataSource) {
		return new NamedParameterJdbcTemplate(dataSource);
	}

	// 创建事务管理器1
	@Bean(name = "h2JdbcManager")
	public PlatformTransactionManager h2JdbcManager(@Qualifier("h2DataSource") DataSource dataSource) {
		DataSourceTransactionManager txManager = new DataSourceTransactionManager(dataSource);
		txManager.setDataSource(dataSource);
		return txManager;
	}

}